<template>
  <el-form label-width="100px">
    <el-form-item label="SKU名称">
      <el-input
        placeholder="SKU名称"
        type="text"
        v-model="skuParams.skuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input
        placeholder="价格(元)"
        type="number"
        v-model="skuParams.price"
      ></el-input>
    </el-form-item>
    <el-form-item label="重量(g)">
      <el-input
        placeholder="重量(g)"
        type="number"
        v-model="skuParams.weight"
      ></el-input>
    </el-form-item>
    <el-form-item label="SKU描述">
      <el-input
        placeholder="SKU描述"
        type="textarea"
        v-model="skuParams.skuDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form :inline="true">
        <el-form-item
          v-for="item in attrArr"
          :key="item.id"
          :label="item.attrName"
        >
          <!-- 给每个属性追加字段attrIdAndValueId -->
          <el-select v-model="item.attrIdAndValueId">
            <el-option
              v-for="attrValue in item.attrValueList"
              :key="attrValue.id"
              :label="attrValue.valueName"
              :value="`${item.id}:${attrValue.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true">
        <el-form-item
          v-for="item in saleArr"
          :key="item.id"
          :label="item.saleAttrName"
        >
          <!-- 给每个属性追加字段saleIdAndValueId-->
          <el-select v-model="item.saleIdAndValueId">
            <el-option
              v-for="saleAttrValue in item.spuSaleAttrValueList"
              :key="saleAttrValue.id"
              :label="saleAttrValue.saleAttrValueName"
              :value="`${item.id}:${saleAttrValue.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table border :data="imgArr" ref="table">
        <el-table-column
          type="selection"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column label="图片">
          <template #="{ row, $index }">
            <img :src="row.imgUrl" alt="" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" @click="handler(row)">
              设置默认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { reqAttr } from '@/api/product/attr'
import type { AttrResponseData, Attr } from '@/api/product/attr/type'
import {
  reqSpuHasSaleAttr,
  reqSpuImageList,
  reqAddSku,
} from '@/api/product/spu'
import type {
  SaleAttrResponseData,
  SpuImgResponseData,
  SaleAttr,
  SpuImg,
  SkuData,
  SpuData,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus'

//平台属性
let attrArr = ref<Attr[]>([])
//销售属性
let saleArr = ref<SaleAttr[]>([])
//照片墙
let imgArr = ref<SpuImg[]>([])
//已有SKU对象
let skuParams = reactive<SkuData>({
  //在init函数传递过来的实参中收集
  category3Id: '', //三级分类的ID
  spuId: '', //已有SPU的ID
  tmId: '', //已有SPU的品牌ID
  //在v-model收集
  skuName: '', //sku名字
  price: '', //sku价格
  weight: '', //sku重量
  skuDesc: '', //sku描述
  //先用v-model收集到（销售）属性对象的新增字段attrIdAndValueId和saleIdAndValueId中，在save方法中处理成服务器需要的格式再真正收集
  skuAttrValueList: [
    //sku平台属性
  ],
  skuSaleAttrValueList: [
    //sku销售属性
  ],
  //在按钮设置默认的回调中收集
  skuDefaultImg: '', //sku图片地址
})
//获得表格组件实例
let table = ref<any>()

//声明接收父组件传递过来的自定义事件
let $emit = defineEmits(['changeScene'])

const initSkuData = async (
  c1Id: number | string,
  c2Id: number | string,
  spu: SpuData,
) => {
  //收集数据（父组件传递的数据这里就可以收集了）
  skuParams.category3Id = spu.category3Id
  skuParams.spuId = spu.id as number
  skuParams.tmId = spu.tmId
  //发送请求获取平台属性数据
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, spu.category3Id)
  attrArr.value = result.data
  //发送请求获取销售属性数据
  let result1: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  saleArr.value = result1.data
  //发送请求获取图片墙数据
  let result2: SpuImgResponseData = await reqSpuImageList(spu.id as number)
  imgArr.value = result2.data
}
//点击设置默认按钮的回调
const handler = (row: SpuImg) => {
  //复选框全部清空后再勾选选中行
  table.value.clearSelection()
  table.value.toggleRowSelection(row, true)
  //收集sku图片地址
  skuParams.skuDefaultImg = row.imgUrl as string
}
//点击取消按钮的回调
const cancel = () => {
  $emit('changeScene', { flag: 0, params: '' })
}
//点击保存按钮的回调
const save = async () => {
  //整理平台属性数据
  skuParams.skuAttrValueList = attrArr.value.reduce((prev: any, next: any) => {
    if (next.attrIdAndValueId) {
      let [attrId, valueId] = next.attrIdAndValueId.split(':')
      prev.push({ attrId, valueId })
    }
    return prev
  }, [])
  //整理销售属性数据
  skuParams.skuSaleAttrValueList = saleArr.value.reduce(
    (prev: any, next: any) => {
      if (next.saleIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(':')
        prev.push({ saleAttrId, saleAttrValueId })
      }
      return prev
    },
    [],
  )
  //发送请求添加SKU
  let result: any = await reqAddSku(skuParams)
  if (result.code == 200) {
    //消息提示
    ElMessage({
      type: 'success',
      message: '添加SKU成功',
    })
    //通知父组件切换为场景0
    $emit('changeScene', { flag: 0, params: '' })
  } else {
    //消息提示
    ElMessage({
      type: 'error',
      message: '添加SKU失败',
    })
  }
}

//暴露方法
defineExpose({ initSkuData })
</script>

<style scoped lang="scss"></style>
